package com.elric.mall.service.impl;

import com.elric.mall.common.utils.ImportExcelUtil;
import com.elric.mall.dto.KzRollbackImportDto;
import com.elric.mall.enums.ImportType;
import com.elric.mall.mapper.KzRollbackMapper;
import com.elric.mall.model.KzRollback;
import com.elric.mall.model.KzRollbackExample;
import com.elric.mall.service.KzRollbackService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.*;

/**
 * 实现功能：
 *
 * @author 作者[Yuxuan.he]
 * @version 1.0.00  2021-09-16 11:21
 */
@Service
public class KzRollbackServiceImpl implements KzRollbackService {
    @Autowired
    private KzRollbackMapper kzRollbackMapper;

    @Override
    public int create(KzRollback kzRollback) {
        return kzRollbackMapper.insert(kzRollback);
    }

    @Override
    public int update(KzRollback kzRollback) {
        return kzRollbackMapper.updateByPrimaryKeySelective(kzRollback);
    }

    @Override
    public KzRollback findById(Long id) {
        return kzRollbackMapper.selectByPrimaryKey(id);
    }

    @Override
    public int delete(Long id) {
        return kzRollbackMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<KzRollback> list(Integer pageSize, Integer pageNum, KzRollback kzRollback) {
        PageHelper.startPage(pageNum, pageSize);
        KzRollbackExample example = new KzRollbackExample();
        if(!StringUtils.isEmpty(kzRollback.getBuildUnitName())) {
            example.createCriteria().andBuildUnitNameLike("%"+kzRollback.getBuildUnitName()+ "%");
        }
        if(!StringUtils.isEmpty(kzRollback.getProjectName())) {
            example.createCriteria().andProjectNameLike("%" + kzRollback.getProjectName() + "%");
        }
        if(!StringUtils.isEmpty(kzRollback.getYear())) {
            example.createCriteria().andYearLike("%" + kzRollback.getYear() + "%");
        }
        return kzRollbackMapper.selectByExample(example);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<KzRollbackImportDto> importDocuments(MultipartHttpServletRequest request) {
        return ImportExcelUtil.readExcelByRequest(request, new KzRollbackImportDto());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertBatch(List<KzRollback> list, ImportType importType) {
        if (importType == ImportType.full) {
            KzRollbackExample example = new KzRollbackExample();
            kzRollbackMapper.deleteByExample(example);
        }
        return kzRollbackMapper.insertBatch(list);
    }
}
